﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using appDataContracts;
using appSupplier.UserControls;
using Microsoft.Win32;
using System.Windows.Media.Imaging;

namespace appSupplier
{
    /// <summary>
    /// Logique d'interaction pour CreateProductWindow.xaml
    /// </summary>
    public partial class CreateProductWindow : Window
    {
        private UCProducts callerUC;
        private bool edit;
        private Stream stream = null;
        private string fileName = string.Empty;


        public CreateProductWindow(List<SerializedCatalog> catalogs, UCProducts callerUC, bool edit)
        {
            InitializeComponent();

            this.callerUC = callerUC;
            this.edit = edit;

            #region Remplissage de la ListBox des catalogues
            if (catalogs != null)
            {
                ListBoxItem item;
                foreach (SerializedCatalog catalog in catalogs)
                {
                    item = new ListBoxItem();
                    item.Content = catalog.CATALOGNAME;
                    item.Tag = catalog.CATALOGID;
                    this.lbCatalogs.Items.Add(item);
                }
            }
            #endregion

            #region Mode edition : pré-remplissage des infos
            if (edit)
            {
                lblTop.Content = "Modification du produit";
                btValidate.Content = "Enregistrer";
                Title = "Modification";
                tbName.Text = ((SerializedProduct)callerUC.dgProducts.SelectedItem).PRODUCTNAME;
                tbDescription.Text = ((SerializedProduct)callerUC.dgProducts.SelectedItem).PRODUCTDESCRIPTION;
                tbPrice.Text = ((SerializedProduct)callerUC.dgProducts.SelectedItem).PRODUCTPRICE.ToString();
                tbImagePath.Text = ((SerializedProduct)callerUC.dgProducts.SelectedItem).PRODUCTIMAGE;

                List<SerializedCatalog> catalogList = AppWindow.supplierService.getProductCatalogs(((SerializedProduct)callerUC.dgProducts.SelectedItem).PRODUCTID);
                List<int> catalogIdList = new List<int>();

                foreach (SerializedCatalog catalog in catalogList)
                {
                    catalogIdList.Add(catalog.CATALOGID);
                }

                foreach (ListBoxItem item in lbCatalogs.Items)
                {
                    if (catalogIdList.Contains(int.Parse(item.Tag.ToString())))
                    {
                        item.IsSelected = true;
                    }
                }
            }
            #endregion

            if (!edit)
            {
                this.Width = 387;
            }
            else
            {
                #region Chargement image
                try
                {

                    myPictureServ.PictureServiceClient client = new myPictureServ.PictureServiceClient();
                    SerializedPictureFile file = client.Download(tbImagePath.Text);
                    Stream s = new MemoryStream(file.PictureStream);

                    img.Source = BitmapFrame.Create(s, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                }
                catch (Exception)
                {

                }
                #endregion
            }
        }

        private void btValidate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                decimal useless = 0;
                if (tbName.Text.Trim() == "")
                {
                    lblError.Content = "Nom requis";
                }
                else if (tbPrice.Text.Trim() == "")
                {
                    lblError.Content = "Prix requis";
                }
                else if (!Decimal.TryParse(tbPrice.Text, out useless))
                {
                    lblError.Content = "Prix incorrect";
                }
                else
                {
                    List<int> catalogsId = new List<int>();
                    foreach (ListBoxItem item in lbCatalogs.SelectedItems)
                    {
                        catalogsId.Add((int)item.Tag);
                    }
                    if (!edit)
                    {
                        string imgPath = tbImagePath.Text;
                        #region upload d'image
                        if (stream != null)
                        {
                            byte[] bytes = new byte[stream.Length];
                            stream.Read(bytes, 0, (int)stream.Length);
                            SerializedPictureFile file = new SerializedPictureFile();
                            file.PictureStream = bytes;
                            file.PictureName = fileName;

                            myPictureServ.PictureServiceClient client = new myPictureServ.PictureServiceClient();
                            client.Upload(file);

                            //http://www.silverlightshow.net/items/Uploading-and-downloading-images-from-WCF-in-Silverlight.aspx
                        }
                        #endregion

                        if (imgPath.Trim() == "")
                        {
                            imgPath = "productdefault.png";
                        }

                        bool test = AppWindow.supplierService.addProduct(new SerializedProduct(0, tbName.Text, decimal.Parse(tbPrice.Text), tbDescription.Text, imgPath, AppWindow.supplier.SUPPLIERID), catalogsId);
                        callerUC.update();
                    }
                    else
                    {
                        string imgPath = tbImagePath.Text;
                        #region upload d'image
                        if (stream != null)
                        {
                            byte[] bytes = new byte[stream.Length];
                            stream.Read(bytes, 0, (int)stream.Length);
                            SerializedPictureFile file = new SerializedPictureFile();
                            file.PictureStream = bytes;
                            file.PictureName = fileName;

                            myPictureServ.PictureServiceClient client = new myPictureServ.PictureServiceClient();
                            client.Upload(file);
                        }
                        #endregion

                        if (imgPath.Trim() == "")
                        {
                            imgPath = "productdefault.png";
                        }

                        int id = ((SerializedProduct)callerUC.dgProducts.SelectedItem).PRODUCTID;
                        bool s = AppWindow.supplierService.updateProduct(new SerializedProduct(id, tbName.Text, Decimal.Parse(tbPrice.Text), tbDescription.Text, tbImagePath.Text, AppWindow.supplier.SUPPLIERID), catalogsId);
                    }
                    callerUC.update();
                    this.Close();
                }
            }
            catch (System.Exception ex)
            {

            }
        }

        private void btCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void tbImagePath_GotMouseCapture(object sender, MouseEventArgs e)
        {

            this.Dispatcher.BeginInvoke(
                new Action(
                delegate
                {

                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = "Images |*.jpg; *.png; *.gif";
                    if (openFileDialog.ShowDialog() == true)
                    {
                        stream = (Stream)openFileDialog.OpenFile();
                        fileName = openFileDialog.SafeFileName;
                        tbImagePath.Text = fileName;
                    }
                }),
                DispatcherPriority.ApplicationIdle);


        }
    }
}
